package com.example.toutiao.ui.main.presenter


import com.example.toutiao.http.HttpUtils
import com.example.toutiao.http.ResponseListener
import com.example.toutiao.http.UserApi
import com.example.toutiao.mvp.model.BaseModel
import com.example.toutiao.mvp.presenter.BasePresenter
import com.example.toutiao.ui.main.model.UserInfoModel
import com.example.toutiao.ui.main.view.UpdateUserInfoView
import okhttp3.MediaType
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.MultipartBody
import okhttp3.RequestBody
import okhttp3.RequestBody.Companion.asRequestBody
import java.io.File

class UpdateUserInfoPresenter: BasePresenter<UpdateUserInfoView>() {
    fun getUserInfo(token:String){
        HttpUtils.sendHttp(HttpUtils.createApi(UserApi::class.java).getUserInfo(token),object :
            ResponseListener<BaseModel<UserInfoModel>> {
            override fun onSuccess(data: BaseModel<UserInfoModel>) {
                if(data!=null&&data.code==200){
                    getBaseView()!!.updateUserInfo(data.data)
                }
            }
            override fun onFail(err: String) {
                getBaseView()!!.setError(err)
            }

        })
    }
    fun uploadImage(file: File,token: String){
        HttpUtils.sendHttp(HttpUtils.createApi(UserApi::class.java).uploadImage(getPartm(file),token),object :ResponseListener<BaseModel<String>> {
            override fun onSuccess(data: BaseModel<String>) {
                if(data!=null&&data.code==200){
                    getBaseView()!!.setData(data.data)
                }
            }
            override fun onFail(err: String) {
                getBaseView()!!.setError(err)
            }

        })
    }
    fun updateInfo(form:MutableMap<String,String>,token: String){
        HttpUtils.sendHttp(HttpUtils.createApi(UserApi::class.java).setPart(token,form),object :ResponseListener<BaseModel<String>> {
            override fun onSuccess(data: BaseModel<String>) {
                if(data!=null&&data.code==200){
                    getBaseView()!!.setData(data.data)
                }
            }
            override fun onFail(err: String) {
                getBaseView()!!.setError(err)
            }

        })
    }
    fun getPartm(file: File): MultipartBody.Part {
        val requestBody: RequestBody= file.asRequestBody("image/*".toMediaTypeOrNull())
        return MultipartBody.Part.createFormData("file",file.name,requestBody)
    }
}